package de.rac.vaadin.framework.ui;
/*******************************************************************************
 * Data for an edit form field that is a list of values from a table source<br>
 * @author Volodymyr Dobryvechir (dobrivecher@yahoo.com)
 * @version 0.2 31.05.2012  <br>
 ******************************************************************************/
import com.vditl.core.DataOrgano;
import com.vaadin.data.Item;
import com.vaadin.ui.*;
import com.oros.db.*;
public class TableListEditFormField extends EditFormField {

	private static final long serialVersionUID = 1L;
	protected Class<?> keyType;
	protected ComboBox tableListCombo;
	protected AETableContainer container;
	protected boolean nullIsAllowed;
	public TableListEditFormField(String colName,String captionResourceName,boolean required,Class<?> keyType,
			String listing,ResourcePool resource) throws Exception
    {
    	super(colName,captionResourceName,required,resource);
    	nullIsAllowed = !required;
    	this.keyType = keyType;
    	String tableName = DataOrgano.GetOutOfRoundBrackets(listing);
    	String colnames=DataOrgano.GetInnerInRoundBrackets(listing);
    	container = resource.getDatabasePool().getAETableContainer(tableName);
    	if (container==null) throw new Exception("Container "+tableName+" does not exist in the pool");
		tableListCombo = new ComboBox(this.caption);
		tableListCombo.setImmediate(true);
		tableListCombo.setNullSelectionAllowed(nullIsAllowed);
		tableListCombo.setContainerDataSource(container);
		tableListCombo.setItemCaptionPropertyId(colnames); //"orgschema.post_name"
		tableListCombo.select(container.firstItemId());
		tableListCombo.setNewItemsAllowed(false);
		tableListCombo.setRequired(required);
    }

	@Override
    public Field getFieldGenerated(Item item) 
    {
		super.getFieldGenerated(item);
       Object res=null;
       Object val = item.getItemProperty(columnName).getValue();
       if (val!=null) res=container.getItem(val);
       if (res==null) 
    	   {
    	       if (nullIsAllowed) tableListCombo.setValue(null);
    	       else
    	       {
    	    	   Object valid = container.firstItemId();
    	    	   if (valid!=null)
    	    	   {
    	    		   item.getItemProperty(columnName).setValue(valid);
    	    		   tableListCombo.setValue(valid);
    	    	   }
    	       }
    	   }
       else tableListCombo.setValue(val);
       setCurrentField(tableListCombo);
       return tableListCombo;
    }
}
